import express,{Request, Response} from "express";
import { body } from "express-validator"
// import { RequestValidationError } from "../errors/request-validation-error"
import { BadRequestError } from "../errors/bad-request-error"
import { validateRequest } from "../middlewares/validate-request"
import { User } from "../models/user"
import jwt from "jsonwebtoken";

const router = express.Router();

router.post('/api/users/signup', [
	body("email").isEmail().withMessage("邮箱验证不通过"),
	body("password").trim().isLength({min:6,max:20}).withMessage("密码长度6到20位")
], validateRequest, async (req:Request, res:Response) => {
	/* throw new DatabaseConnectionError();
	// throw new Error("数据库连接失败");
	const { email, password } = req.body;
	console.log("创建用户");
	res.send({});*/
       const { email, password } = req.body;
       const existingUser = await User.findOne({ email });
       if (existingUser) {
       	console.log("用户已存在");
	throw new BadRequestError("邮箱已存在");
	// return res.send({});
       }

       const user = User.build({ email, password });
       await user.save();

       // if (!process.env.JWT_KEY) throw new Error("获取不到JWT_KEY");
       const userJwt = jwt.sign({ id: user.id, email: user.email }, process.env.JWT_KEY!);

       req.session = {
       	jwt: userJwt
       };

       res.status(201).send(user);
});

export { router as signupRouter };
